const dayjs = require('dayjs')
const catchAsync = require('../utils/catchAsync')
const User = require('../models/user')
const Article = require('../models/article')
const Tag = require('../models/tag')
const Category = require('../models/category')
const Review = require('../models/reviewModel')
const Visit = require('../models/visitModel')

/**
 * 获取文章，分类，标签，用户，评论的统计数据
 */
exports.getStatsData = catchAsync(async (req, res, next) => {
  // 并行执行，提升性能
  const [userCount, articleCount, tagCount, categoryCount, reviewCount] = await Promise.all([
    User.estimatedDocumentCount(),
    Article.estimatedDocumentCount(),
    Tag.estimatedDocumentCount(),
    Category.estimatedDocumentCount(),
    Review.estimatedDocumentCount(),
  ])

  res.status(200).json({
    status: 'success',
    data: {
      userCount,
      articleCount,
      tagCount,
      categoryCount,
      reviewCount,
    },
  })
})

/**
 * 获取指定时间段的访问统计
 */
exports.getVisitStats = catchAsync(async (req, res, next) => {
  // 默认过去7天
  const days = +req.query.days || 7

  // 计算时间范围
  const startDate = dayjs()
    .subtract(days - 1, 'day')
    .startOf('day')
    .toDate()
  const endDate = dayjs().endOf('day').toDate()

  // 聚合：按天统计访问量
  const stats = await Visit.aggregate([
    {
      $match: {
        date: { $gte: startDate, $lte: endDate },
      },
    },
    {
      $group: {
        _id: { $dateToString: { format: '%Y-%m-%d', date: '$date' } },
        count: { $sum: 1 },
      },
    },
    { $sort: { _id: 1 } },
  ])

  const result = stats.map((s) => ({
    date: s._id,
    count: s.count,
  }))

  res.status(200).json({
    status: 'success',
    data: result,
  })
})
